package tools.vetorial;

import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.util.List;

import core.DrawContext;
import core.DrawTool;
import core.Object2D;
import core.VectorialObject;
import core.VectorialSelectionTree.Node;

public class VectorialSelectionTool extends DrawTool {

	private Node mPressedNode ;
	
	@Override
	public void dispose(DrawContext ctx) {
		ctx.clearSelection();
	}

	@Override
	public void init(DrawContext ctx) {
		// TODO Auto-generated method stub

	}

	@Override
	public void processKeyEvent(KeyEvent evt, DrawContext context) {
		// TODO Auto-generated method stub

	}

	@Override
	public void processMouseEvent(MouseEvent evt, DrawContext context) {
		
		switch(evt.getID()){
		case MouseEvent.MOUSE_CLICKED:
			
			if(!evt.isControlDown()) {
				context.clearSelection();
			}
			
			VectorialObject v = intersects(evt.getX(), evt.getY(), context);
			
			if(v != null) {
				System.out.printf("Point (%d,%d) intersects object", evt.getX(), evt.getY());
				context.addToSelection(v);
			}
			else {
				context.clearSelection();
			}
			context.setChanged(true);
			
			break;
	
		case MouseEvent.MOUSE_PRESSED:
			
			if(context.hasSelection()) {
				
				List<Node> nodes = 
					context.getVectorialSelectionTree().getIntersectionNodes(
						new Point2D.Double(evt.getX(), evt.getY()) , 5);
				
				if(nodes.size() > 0){
					mPressedNode = nodes.get(0);
					System.out.println("Node pressed");
				}
			}
			
			break;
			
		case MouseEvent.MOUSE_RELEASED:
			
			if(mPressedNode != null) {
				context.getVectorialSelectionTree().updateNode(mPressedNode);
			}
			
			mPressedNode = null;
			break;
			
		case MouseEvent.MOUSE_DRAGGED:
			
			if(mPressedNode != null) {
				mPressedNode.point.x = evt.getX();
				mPressedNode.point.y = evt.getY();
				
				context.setChanged(true);
			}
			
			break;
		}

	}
	
	private VectorialObject intersects(int x, int y, DrawContext ctx) {
		
		Point2D.Double pt = new Point2D.Double(x, y);
		
		for(Object2D o : ctx.getObjects()) {
			if(o instanceof VectorialObject) {
				VectorialObject v = (VectorialObject) o;
				
				if(v.intersect(pt)) {
					return v;
				}
			}
		}
		
		return null;
	}

}
